<template>
  <em-cell-group title="自定义数据">
    <rich-field
      v-for="(item,index) in items"
      :key="index"
      :value="item"
      @remove="onDelete($event,index)"
      @move="onMove($event,index)"
      @input="onChange($event,index)"
    />
    <rich-field
      v-for="(mock,index) in mockItems"
      :key="'mock-'+index"
      :value="mock"
      @input="onChange"
    />
    <el-button
      v-if="canAdd"
      class="btn-edit"
      icon="el-icon-plus"
      :round="false"
      @click="onAddItem"
    >添加一个{{ dataItemText }}</el-button>
  </em-cell-group>
</template>

<script>
import RichField from '@/components/RichField'
export default {
  name: 'DataOption',
  components: {
    RichField
  },
  props: {
    value: {
      type: Array,
      required: true
    },
    setting: {
      type: Object,
      default: null
    },
    dataItemText: {
      type: String,
      default: '数据项'
    }
  },
  data() {
    return {
      placeitem: {
        thumb: '',
        title: ''
      }
    }
  },
  computed: {
    items: {
      get() {
        return this.value
      },
      set(v) {
        this.value = v
      }
    },
    canAdd() {
      if (!this.setting) {
        return true
      }
      var size = this.mockItems.length + this.items.length
      var maxSize = 0
      if (this.setting.maxItems) {
        maxSize = this.setting.maxItems
      } else if (this.setting.maxCols && this.setting.maxRows) {
        maxSize = this.setting.maxCols * this.setting.maxRows
      }
      if (size >= maxSize) {
        return false
      }
      return true
    },
    mockItems() {
      var size = this.mockSize - this.items.length
      if (size > 0) {
        return new Array(size).fill({
          thumb: '',
          title: ''
        })
      }
      return []
    }
  },
  mounted() {},
  methods: {
    onChange(d, index) {
      if (index === undefined) {
        this.items.push(d)
      } else {
        this.$set(this.items, index, d)
      }
    },
    onDelete(item, index) {
      // 删除后一项
      this.items.splice(index, 1)
    },
    onMove(val, index) {
      if (val > 0) {
        this.down(index)
      }
      if (val < 0) {
        this.up(index)
      }
    },
    up(index) {
      if (index === 0) {
        return
      }
      // 在上一项插入该项
      this.items.splice(index - 1, 0, this.items[index])
      // 删除后一项
      this.items.splice(index + 1, 1)
    },
    down(index) {
      if (index === this.items.length - 1) {
        return
      }
      // 在下一项插入该项
      this.items.splice(index + 2, 0, this.items[index])
      // 删除前一项
      this.items.splice(index, 1)
    },
    onAddItem() {
      this.items.push({
        thumb: '',
        title: ''
      })
    }
  }
}
</script>

